package com.kitty.record.kittyalgorithm.audition;



/**
 * 请设计一个栈，除了常规栈支持的pop与push函数以外，
 * 还支持min函数，该函数返回栈元素中的最小值。
 * 执行push、pop和min操作的时间复杂度必须为O
 * (1)示例：
 * MinStack minStack = new MinStack();
 * minStack.push(-2);
 * minStack.push(0);
 * minStack.push(-3);
 * minStack.getMin();   --> 返回 -3.
 * minStack.pop();
 * minStack.top();      --> 返回 0.
 * minStack.getMin();   --> 返回 -2.
 */
public class LeetCode0302 {
    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);
        System.out.println("minStack.getMin() = " + minStack.getMin());

    }

    private static class  MinStack {
        private ListNode listNode;


        /** initialize your data structure here. */
        public MinStack() {

        }

        public void push(int x) {
            if(this.empty()){
                listNode = new ListNode(x,x,null);
            }
            listNode = new ListNode(x,Math.min(x,listNode.min),listNode);
        }
        //出栈，删除链表的头部
        public void pop() {
            if(this.empty()){
                throw new IllegalStateException("栈为空。。。");
            }
            listNode = listNode.next;
        }
        //栈顶的值就是链表头部的值
        public int top() {
            if(this.empty()){
                throw new IllegalStateException("栈为空。。。");
            }
            return listNode.val;
        }

        public int getMin() {
            if(this.empty()){
                throw new IllegalStateException("栈为空。。。");
            }
            return listNode.min;
        }

        private boolean empty(){
            return listNode == null;
        }
    }


    private static class ListNode {
        public int val;
        public int min;//最小值
        public ListNode next;

        public ListNode(int val, int min, ListNode next) {
            this.val = val;
            this.min = min;
            this.next = next;
        }
    }

}

